import { serviceStart, serviceStop } from "@/api/modules/service/service";
import DialogBox from "@/components/DialogBox";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { ProductStatusEnum } from "@/enums/statusEnum";
import { useApplet } from "@/hooks/useApplet";
import { useAuthButtonList } from "@/hooks/useAuthButtons";
import { filePrefix } from "@/hooks/useSystem";
import { DictType, getDictList } from "@/utils/cacheUtil";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import AppletLogo from "@public/images/applet/applet.png";
import { useRouter } from "vue-router";
import {
	addUserApplet,
	delUserApplet,
	getMarketAppletList,
	marketInstall,
	modUserApplet
} from "../../../api/modules/applet/userApplet";
import "../applet.scss";
import BasicDialog from "../components/detailDialog";
import { Applet } from "./../../../api/interface/iot";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const router = useRouter();
		const initParam = reactive<Applet.ReqUserApplet>({ pageSize: 12 });
		const { gotoAccess } = useApplet();

		const dataCallback = (data: any) => {
			data.records.map((item: any) => {
				item.status = item.status + "";
				return item;
			});
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current || 1,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			return getMarketAppletList(params);
		};
		const buttonsList = ref<any>([]);
		const operateList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			let btns = await useAuthButtonList();
			buttonsList.value = btns.filter((item: any) => item.type == "btn");
			operateList.value = btns.filter((item: any) => (item.type = "operate"));
		});
		const detailDialog = reactive<any>({
			title: proxy?.$t("mall.dialog_title.add"),
			detail: {},
			visible: false
		});
		const clickBtn = async (fn: string, row: any) => {
			let selected: any[] = row.selectList ? row.selectList : row.id ? [row] : [row.row];
			switch (fn) {
				case "mod":
					if (selected.length != 1) {
						showMsg(proxy?.$t("mall.msg.mod"), MessageType.warning);
						return;
					}
					detailDialog.detail = selected[0];
					detailDialog.title = proxy?.$t("mall.dialog_title.mod");
					detailDialog.visible = true;
					break;
				case "detail":
					if (selected.length != 1) {
						showMsg(proxy?.$t("mall.msg.detail"), MessageType.warning);
						return;
					}
					router.push({ path: RouterPath.appletDetail, query: { id: selected[0].id, key: selected[0].key } });
					break;
				case "add":
					detailDialog.detail = {};
					detailDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("mall.msg.del"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("mall.confirm.del") }).then(flag => {
						flag && submitDel({ id: selected.map(item => item.id).join(",") });
					});
					break;
				case "copy":
					if (selected.length != 1) {
						showMsg(proxy?.$t("mall.msg.copy"), MessageType.warning);
						return;
					}
					copyProductDialog.visible = true;
					copyProductDialog.formData = JSON.parse(JSON.stringify(selected[0]));
					copyProductDialog.formData.id = selected[0].model;
					break;
				case "start":
					if (selected.length != 1) {
						showMsg(proxy?.$t("mall.msg.start"), MessageType.warning);
						return;
					}
					startService(selected);
					break;
				case "stop":
					if (selected.length != 1) {
						showMsg(proxy?.$t("mall.msg.stop"), MessageType.warning);
						return;
					}
					stopService(selected);
					break;
			}
		};

		const startService = async (selected: any) => {
			let { code, message } = await serviceStart({ id: selected[0].svcId });
			showTips(code, proxy?.$t("mall.tips.start"), message);
		};
		const stopService = async (selected: any) => {
			let { code, message } = await serviceStop({ id: selected[0].svcId });
			showTips(code, proxy?.$t("mall.tips.stop"), message);
		};
		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			// { prop: "model", label: "应用编码", search: { el: "input" } },
			{ prop: "name", label: proxy?.$t("mall.tablist_label.name"), search: { el: "input" } },
			// { prop: "status", label: "应用状态", search: { slot: {} } },
			// { prop: "deviceType", label: "应用类型", search: { slot: {} } },
			// { prop: "deptName", label: "所属分组", search: { slot: {} } },
			{ prop: "descript", label: proxy?.$t("mall.tablist_label.descript") },
			{ prop: "createTime", label: proxy?.$t("mall.tablist_label.create_time") },
			{ prop: "operation", label: proxy?.$t("mall.tablist_label.operation"), fixed: "right", width: 130 }
		];

		const proTable = ref<any>();
		const submitDel = async (dataInfo: any) => {
			let res = await delUserApplet({ ...dataInfo });
			let ok = showTips(res.code, proxy?.$t("mall.tips.del"), res.message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		const submitAdd = async () => {
			let api = detailDialog.detail.id ? modUserApplet : addUserApplet;
			let res = await api({ ...detailDialog.detail });
			let ok = showTips(res.code, proxy?.$t("mall.tips.add"), res.message);
			if (ok) {
				detailDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		const copyProductDialog = reactive<any>({
			visible: false,
			formData: {}
		});
		const typeObj = ref<any>({});
		getDictList(DictType.AppletType).then(list => {
			list.map(item => {
				typeObj.value[item.key] = item.label;
			});
		});
		const install = async () => {
			let { code, message } = await marketInstall(installDialog.detail);
			let ok = showTips(code, proxy?.$t("mall.tips.install"), message);
			if (ok) {
				installDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		const installDialog = reactive<any>({
			title: proxy?.$t("mall.dialog_title.install"),
			detail: { id: "", oldAppKey: "" },
			visible: false
		});
		return () => {
			return (
				<div class="applet-page">
					{/* <div style="width:100px">
						<TypedJs prefix={`组态信息 `} dataList={[`打字机打字机打字机打字机打字机打字机打字机打字机打字机打字机打字机`]} />
					</div> */}
					<DialogBox width="500" title={installDialog.title} v-model:visible={installDialog.visible} onConfirm={() => install()}>
						<el-form label-width="100">
							<el-form-item label={proxy?.$t("mall.form_label.install")}>
								<el-input v-model={installDialog.detail.oldAppKey} disabled></el-input>
							</el-form-item>
							{/* <el-form-item label="新应用标识">
								<el-input v-model={installDialog.detail.newAppKey} placeholder="请输入新应用标识"></el-input>
							</el-form-item> */}
						</el-form>
					</DialogBox>
					<BasicDialog
						width="800px"
						title={detailDialog.title}
						v-model:visible={detailDialog.visible}
						detail={detailDialog.detail}
						onSubmit={submitAdd}
					></BasicDialog>
					<ProTable
						ref={proTable}
						title={buttonsList.value.length ? "" : proxy?.$t("mall.tab_title.market")}
						columns={columns}
						noList
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
						searchCol={5}
						toolbar={["grid"]}
						viewType="grid"
						gridSpan={8}
						showHeader={false}
					>
						{{
							tableHeader: (scope: any) => {
								return buttonsList.value?.map((item: any) => {
									return (
										<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
											<i class={`iconfont ${item.icon}`}></i>
											{item.menuName}
										</el-button>
									);
								});
							},
							cardBody: (scope: any) => {
								return (
									<div class="applet-card shadow-md">
										<div class="bg"></div>
										<div class="applet-container">
											{/* <div class="flex justify-between p-3">
												<div>{scope.row.marketDeployType == "dev" ? "端应用" : "云应用"}</div>
												<div>{typeObj.value[scope.row.appType]}</div>
											</div> */}
											<div class="flex p-6">
												<el-image
													class="mr-5"
													style="width:180px;height:150px;"
													src={scope.row.logo ? `${filePrefix()}${scope.row.logo}` : AppletLogo}
													fit="fill"
												></el-image>

												<div class="flex flex-1 flex-col">
													<div class="flex justify-between mb-2">
														<div class="font-bold text-lg">{scope.row.name}</div>
														<div class="flex items-center gap-2">
															<el-tag>
																{scope.row.marketDeployType == "dev" ? proxy?.$t("mall.tag.side") : proxy?.$t("mall.tag.cloud")}
															</el-tag>
															<el-tag type="success">{typeObj.value[scope.row.appType]}</el-tag>
														</div>
													</div>
													<div class="text-sm w-full line-clamp-3 text-gray-400">{scope.row.desc}</div>
													<div class="mt-auto">
														<el-button
															type={scope.row.marketDeployType == "dev" ? "primary" : "success"}
															onClick={() => {
																if (scope.row.marketDeployType == "dev") {
																	installDialog.visible = true;
																	installDialog.detail.id = scope.row.id;
																	installDialog.detail.oldAppKey = scope.row.key;
																	installDialog.detail.newAppKey = scope.row.key;
																} else {
																	gotoAccess(scope.row);
																}
															}}
														>
															{scope.row.marketDeployType == "dev" ? proxy?.$t("mall.btn.access") : proxy?.$t("mall.btn.trial")}
															{/* <i class="iconfont iconarrow-right ml-2" style="font-size:14px" /> */}
														</el-button>
													</div>
												</div>
											</div>
										</div>
									</div>
								);
							},
							status: (scope: any) => {
								return (
									<OnlineStatus
										v-model={scope.row.status}
										onlineLabel={ProductStatusEnum.DEPLOY_LABEL}
										offlineLabel={ProductStatusEnum.DEVELOP_LABEL}
									/>
								);
							},
							model: (scope: any) => {
								return (
									<el-link type="primary" onClick={() => clickBtn("details", scope.row)}>
										{scope.row.model}
									</el-link>
								);
							},
							createTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							operation: (scope: any) => {
								return (
									<>
										<el-link
											type="primary"
											link
											class="iconfont iconbx-file"
											onClick={() => {
												clickBtn("details", scope.row);
											}}
										>
											{proxy?.$t("mall.link.detail")}
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<Empty
										class="text-left leading-6"
										subtitle={proxy?.$t("mall.empty.subtitle")}
										title={proxy?.$t("mall.empty.title")}
										btnText={proxy?.$t("mall.empty.btn_text")}
										showButton={false}
									/>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
